#!/usr/bin/env python3
"""
AI选股器模块 - 基于人工智能的股票选择器
提供题材分析、智能选股、风险评估和购买建议功能
"""

import easyquotation
import logging
import time
import requests
import json
from typing import Dict, List, Optional
from dataclasses import dataclass
from enum import Enum
from datetime import datetime
import os


class ThemeType(Enum):
    """题材类型枚举 - 扩展为更全面的题材分析"""
    TECHNOLOGY = "科技股"
    NEW_ENERGY = "新能源"
    HEALTHCARE = "医药医疗"
    CONSUMPTION = "消费"
    FINANCE = "金融"
    CYCLE = "周期"
    MILITARY = "军工"
    INFRASTRUCTURE = "基建"
    EXPORT = "出口"
    AI = "人工智能"
    SEMICONDUCTOR = "半导体芯片"
    AUTO = "汽车产业"
    REAL_ESTATE = "房地产"
    ENVIRONMENT = "环保"
    AVIATION = "航空航天"
    CHEMICAL = "化工"
    AGRICULTURE = "农业"
    COMMUNICATION = "通信"
    EDUCATION = "教育"
    TOURISM = "旅游酒店"
    MEDIA = "传媒"
    SUPPLY_CHAIN = "供应链物流"
    BIOTECH = "生物科技"
    FINTECH = "金融科技"
    INTERNET = "互联网"
    GAMING = "游戏"
    ESG = "ESG概念"
    METAVERSE = "元宇宙"
    BLOCKCHAIN = "区块链"
    QUANTUM = "量子科技"


class RiskLevel(Enum):
    """风险等级枚举"""
    LOW = ("低风险", 1)
    MEDIUM = ("中风险", 2)
    HIGH = ("高风险", 3)
    VERY_HIGH = ("极高风险", 4)


@dataclass
class StockInfo:
    """股票信息数据类"""
    code: str
    name: str
    price: float
    change_pct: float
    volume: int
    market_cap: float
    theme: ThemeType
    score: float
    risk_level: RiskLevel


@dataclass
class ThemeAnalysis:
    """题材分析结果"""
    theme: ThemeType
    hot_score: float  # 热度评分 0-100
    trend_score: float  # 趋势评分 0-100
    risk_score: float  # 风险评分 0-100
    top_stocks: List[StockInfo]
    recommendation: str


@dataclass
class MonthlyThemePattern:
    """月度题材炒作规律"""
    month: int
    hot_themes: List[str]
    success_rate: float
    typical_duration: str
    historical_notes: str


@dataclass
class AIAnalysisResult:
    """AI分析结果 - 支持R1模型增强字段"""
    market_sentiment: str
    trend_prediction: str
    risk_assessment: str
    investment_suggestion: str
    confidence_score: float
    
    # R1模型增强字段
    key_themes: Optional[List[str]] = None
    risk_factors: Optional[List[str]] = None
    position_advice: Optional[str] = None


@dataclass
class SelectionResult:
    """选股结果"""
    recommended_stocks: List[StockInfo]
    theme_analysis: List[ThemeAnalysis]
    market_overview: Dict
    risk_warning: str
    strategy_advice: str
    ai_analysis: Optional[AIAnalysisResult] = None
    monthly_patterns: Optional[List[MonthlyThemePattern]] = None


class DeepSeekAI:
    """DeepSeek AI 集成类 - 升级支持R1模型"""
    
    def __init__(self, api_key: str = None, model: str = "deepseek-reasoner"):
        """初始化DeepSeek AI
        
        Args:
            api_key: DeepSeek API密钥 (如果不提供将从环境变量获取)
            model: 使用的模型版本 (deepseek-reasoner, deepseek-chat等)
        """
        self.api_key = api_key or os.getenv('DEEPSEEK_API_KEY', 'sk-placeholder')
        self.base_url = "https://api.deepseek.com/v1/chat/completions"
        self.model = model
        
        # R1推理模型特殊配置
        if model == "deepseek-reasoner":
            self.reasoning_enabled = True
            self.max_reasoning_tokens = 50000  # R1推理模型支持长推理链
            self.temperature = 0.3  # R1推理模型推荐较低温度
        else:
            self.reasoning_enabled = False
            self.max_reasoning_tokens = None
            self.temperature = 0.7
        
    def analyze_market_data(self, market_data: Dict, theme_data: List[Dict]) -> AIAnalysisResult:
        """使用DeepSeek AI分析市场数据"""
        try:
            prompt = self._create_market_analysis_prompt(market_data, theme_data)
            response = self._call_deepseek_api(prompt)
            return self._parse_ai_response(response)
        except Exception as e:
            # 如果AI调用失败，返回默认分析
            return AIAnalysisResult(
                market_sentiment="中性",
                trend_prediction="需要更多数据分析",
                risk_assessment="中等风险",
                investment_suggestion="建议谨慎投资，分散风险",
                confidence_score=50.0
            )
    
    def _create_market_analysis_prompt(self, market_data: Dict, theme_data: List[Dict]) -> str:
        """创建市场分析提示词 - 针对R1模型优化"""
        if self.reasoning_enabled:
            # R1模型使用更详细的推理提示
            prompt = f"""
你是一位具有20年经验的资深股票分析师和量化投资专家。请运用你的专业知识和推理能力，对以下A股市场数据进行深度分析。

<market_data>
市场概况:
- 市场状态: {market_data.get('status', '未知')}
- 平均热度: {market_data.get('avg_score', 0):.2f}
- 热门题材: {', '.join(market_data.get('hot_themes', []))}
- 分析时间: {datetime.now().strftime('%Y-%m-%d %H:%M')}

题材详细分析数据:
"""
            for i, theme in enumerate(theme_data[:8], 1):  # R1模型可以处理更多数据
                prompt += f"{i}. {theme.get('name', '未知题材')}: 热度{theme.get('hot_score', 0):.1f}/100, 趋势{theme.get('trend_score', 0):.1f}/100, 风险{theme.get('risk_score', 0):.1f}/100\n"
        
            prompt += """
</market_data>

请按照以下步骤进行深度分析：

1. **市场环境分析**: 
   - 分析当前A股市场的整体状况
   - 评估宏观经济环境对股市的影响
   - 判断资金流向和市场情绪

2. **题材热度分析**:
   - 识别当前最热门的投资题材
   - 分析各题材的可持续性和风险
   - 预测题材轮动的可能性

3. **技术面分析**:
   - 基于热度和趋势数据判断技术走势
   - 评估支撑位和阻力位
   - 分析成交量和资金流向

4. **风险评估**:
   - 识别主要风险因素
   - 评估市场波动性
   - 分析政策风险和系统性风险

5. **投资策略建议**:
   - 提供具体的投资建议
   - 建议仓位配置
   - 给出风险控制措施

请以JSON格式输出分析结果，包含以下字段:
{
    "market_sentiment": "市场情绪(乐观/谨慎乐观/中性/谨慎悲观/悲观)",
    "trend_prediction": "短期趋势预测(强势上涨/温和上涨/震荡整理/温和下跌/深度调整)",
    "risk_assessment": "风险等级(低风险/中低风险/中等风险/中高风险/高风险)",
    "investment_suggestion": "详细投资建议(包含具体操作建议)",
    "confidence_score": 置信度评分(0-100),
    "key_themes": ["重点关注题材1", "重点关注题材2", "重点关注题材3"],
    "risk_factors": ["风险因素1", "风险因素2", "风险因素3"],
    "position_advice": "仓位建议(如：建议仓位60-70%)"
}
"""
        else:
            # 传统模型使用简化提示
            prompt = f"""
作为专业的股票分析师，请基于以下数据进行深度分析：

市场概况:
- 市场状态: {market_data.get('status', '未知')}
- 平均热度: {market_data.get('avg_score', 0)}
- 热门题材: {', '.join(market_data.get('hot_themes', []))}

题材分析数据:
"""
            for theme in theme_data[:5]:  # 只分析前5个热门题材
                prompt += f"- {theme.get('name', '未知题材')}: 热度{theme.get('hot_score', 0):.1f}, 风险{theme.get('risk_score', 0):.1f}\n"
        
            prompt += """
请从以下维度进行分析:
1. 市场情绪判断 (乐观/中性/悲观)
2. 短期趋势预测 (上涨/震荡/下跌)
3. 风险评估 (高/中/低风险)
4. 投资建议 (具体可操作的建议)
5. 置信度评分 (0-100分)

请用JSON格式回复，包含以下字段:
{
    "market_sentiment": "市场情绪",
    "trend_prediction": "趋势预测",
    "risk_assessment": "风险评估",
    "investment_suggestion": "投资建议",
    "confidence_score": 置信度分数
}
"""
        return prompt
    
    def _call_deepseek_api(self, prompt: str) -> str:
        """调用DeepSeek API - 支持R1模型"""
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        
        # 构建请求数据
        data = {
            "model": self.model,
            "messages": [
                {"role": "user", "content": prompt}
            ],
            "temperature": self.temperature,
        }
        
        # R1模型特殊参数
        if self.reasoning_enabled:
            data["max_tokens"] = 8000  # R1模型支持更长输出
            data["max_reasoning_tokens"] = self.max_reasoning_tokens
            data["reasoning_effort"] = "high"  # 启用高质量推理
        else:
            data["max_tokens"] = 500
        
        try:
            # R1模型可能需要更长的处理时间
            timeout = 60 if self.reasoning_enabled else 30
            response = requests.post(self.base_url, headers=headers, json=data, timeout=timeout)
            
            if response.status_code == 200:
                result = response.json()
                
                # 处理R1模型的响应格式
                if self.reasoning_enabled and 'choices' in result:
                    choice = result['choices'][0]
                    if 'message' in choice:
                        # 提取推理过程和最终答案
                        message = choice['message']
                        content = message.get('content', '')
                        
                        # 如果有推理过程，可以记录日志
                        if 'reasoning' in message:
                            reasoning = message['reasoning']
                            self._log_reasoning_process(reasoning)
                        
                        return content
                    
                return result['choices'][0]['message']['content']
            else:
                error_msg = f"API调用失败: {response.status_code}"
                if response.text:
                    error_msg += f", 错误信息: {response.text}"
                raise Exception(error_msg)
                
        except requests.exceptions.Timeout:
            raise Exception("DeepSeek API调用超时，请稍后重试")
        except Exception as e:
            raise Exception(f"DeepSeek API调用错误: {e}")
    
    def _log_reasoning_process(self, reasoning: str):
        """记录R1模型的推理过程"""
        if len(reasoning) > 200:
            # 只记录推理过程的开头部分
            reasoning_summary = reasoning[:200] + "..."
        else:
            reasoning_summary = reasoning
        
        print(f"🧠 DeepSeek R1推理过程: {reasoning_summary}")
        # 可以选择性地记录到日志文件中
    
    def _parse_ai_response(self, response: str) -> AIAnalysisResult:
        """解析AI响应 - 支持R1模型增强格式"""
        try:
            # 尝试解析JSON响应
            import re
            json_match = re.search(r'\{.*\}', response, re.DOTALL)
            if json_match:
                data = json.loads(json_match.group())
                
                # 构建基础分析结果
                result = AIAnalysisResult(
                    market_sentiment=data.get('market_sentiment', '中性'),
                    trend_prediction=data.get('trend_prediction', '震荡整理'),
                    risk_assessment=data.get('risk_assessment', '中等风险'),
                    investment_suggestion=data.get('investment_suggestion', '建议谨慎投资'),
                    confidence_score=float(data.get('confidence_score', 50.0))
                )
                
                # R1模型增强字段处理
                if self.reasoning_enabled:
                    # 处理重点题材
                    key_themes = data.get('key_themes', [])
                    if key_themes:
                        result.key_themes = key_themes
                    
                    # 处理风险因素
                    risk_factors = data.get('risk_factors', [])
                    if risk_factors:
                        result.risk_factors = risk_factors
                    
                    # 处理仓位建议
                    position_advice = data.get('position_advice', '')
                    if position_advice:
                        result.position_advice = position_advice
                        # 将仓位建议整合到投资建议中
                        result.investment_suggestion += f"\n\n仓位配置: {position_advice}"
                    
                    # 如果有重点题材，添加到投资建议中
                    if key_themes:
                        themes_text = "、".join(key_themes)
                        result.investment_suggestion += f"\n\n重点关注题材: {themes_text}"
                
                return result
                
        except Exception as e:
            print(f"⚠️ JSON解析失败: {e}")
        
        # 如果JSON解析失败，尝试文本解析
        try:
            # 使用正则表达式提取关键信息
            sentiment_patterns = {
                '乐观': ['乐观', '看好', '积极', '向好'],
                '悲观': ['悲观', '看空', '下跌', '调整'],
                '中性': ['中性', '震荡', '整理', '观望']
            }
            
            trend_patterns = {
                '上涨': ['上涨', '上升', '向上', '突破'],
                '下跌': ['下跌', '下降', '向下', '回调'],
                '震荡': ['震荡', '整理', '横盘', '盘整']
            }
            
            # 分析文本内容
            sentiment = '中性'
            trend = '震荡整理'
            
            for key, patterns in sentiment_patterns.items():
                if any(pattern in response for pattern in patterns):
                    sentiment = key
                    break
            
            for key, patterns in trend_patterns.items():
                if any(pattern in response for pattern in patterns):
                    trend = key
                    break
            
            return AIAnalysisResult(
                market_sentiment=sentiment,
                trend_prediction=trend,
                risk_assessment="中等风险",
                investment_suggestion=response[:500] + "..." if len(response) > 500 else response,
                confidence_score=70.0 if self.reasoning_enabled else 60.0
            )
            
        except Exception as e:
            print(f"⚠️ 文本解析失败: {e}")
        
        # 最后的备用方案
        return AIAnalysisResult(
            market_sentiment="中性",
            trend_prediction="需要更多数据",
            risk_assessment="中等风险", 
            investment_suggestion="AI分析暂时不可用，建议结合技术面和基本面进行综合判断。",
            confidence_score=40.0
        )


class AIStockSelector:
    """真正的AI选股器主类 - 集成DeepSeek AI分析"""
    
    def __init__(self, data_source: str = 'tencent', use_ai: bool = True):
        """初始化AI选股器
        
        Args:
            data_source: 数据源类型 ('sina' 或 'tencent')
            use_ai: 是否启用DeepSeek AI分析
        """
        self.data_source = data_source
        self.use_ai = use_ai
        self.quotation = None
        self.logger = self._setup_logging()
        self._initialize_quotation()
        
        # 集成DeepSeek AI
        if self.use_ai:
            try:
                # 默认使用R1推理模型，如果失败则降级到chat模型
                try:
                    self.deepseek_ai = DeepSeekAI(model="deepseek-reasoner")
                    self.logger.info("DeepSeek R1推理模型初始化成功")
                except Exception as r1_error:
                    self.logger.warning(f"DeepSeek R1推理模型初始化失败: {r1_error}, 尝试使用chat模型")
                    self.deepseek_ai = DeepSeekAI(model="deepseek-chat")
                    self.logger.info("DeepSeek Chat模型初始化成功")
            except Exception as e:
                self.logger.warning(f"DeepSeek AI初始化失败: {e}, 将使用传统算法")
                self.use_ai = False
                self.deepseek_ai = None
        else:
            self.deepseek_ai = None
        
        # 扩展的题材股票池
        self.theme_stocks = self._init_comprehensive_theme_stocks()
        
        # 月度题材炒作规律
        self.monthly_patterns = self._init_monthly_patterns()
        
    def _setup_logging(self) -> logging.Logger:
        """设置日志"""
        logger = logging.getLogger('AIStockSelector')
        logger.setLevel(logging.INFO)
        
        if not logger.handlers:
            handler = logging.StreamHandler()
            formatter = logging.Formatter(
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
            )
            handler.setFormatter(formatter)
            logger.addHandler(handler)
            
        return logger
    
    def _initialize_quotation(self):
        """初始化行情服务"""
        try:
            if self.data_source.lower() == 'sina':
                self.quotation = easyquotation.use('sina')
            else:
                self.quotation = easyquotation.use('tencent')
            self.logger.info(f"AI选股器初始化成功，数据源：{self.data_source}")
        except Exception as e:
            self.logger.error(f"初始化行情服务失败：{e}")
            raise
    
    def _init_comprehensive_theme_stocks(self) -> Dict[ThemeType, List[str]]:
        """初始化全面的题材股票池"""
        return {
            ThemeType.TECHNOLOGY: [
                '000858', '002415', '300059', '300760', '688036', '688008',
                '002049', '300496', '300601', '002230', '600570', '002253'
            ],
            ThemeType.NEW_ENERGY: [
                '300750', '002594', '300014', '002466', '300274', '603799',
                '300450', '002179', '300763', '300724', '002459', '688005'
            ],
            ThemeType.HEALTHCARE: [
                '300015', '000538', '300347', '600276', '300122', '002007',
                '300595', '600161', '300601', '002821', '000423', '600521'
            ],
            ThemeType.CONSUMPTION: [
                '000858', '002304', '600519', '000596', '002311', '600036',
                '000895', '002032', '600309', '000568', '000799', '600887'
            ],
            ThemeType.FINANCE: [
                '600036', '000001', '601318', '601166', '600000', '000002',
                '601328', '600016', '600837', '601169', '601398', '601288'
            ],
            ThemeType.MILITARY: [
                '600150', '002179', '000738', '600967', '002013', '000625',
                '002151', '600893', '000901', '002465', '002025', '600038'
            ],
            ThemeType.AI: [
                '002415', '300059', '002049', '300496', '600570', '002230',
                '300033', '002253', '300454', '600100', '000066', '300558'
            ],
            ThemeType.SEMICONDUCTOR: [
                '002049', '688008', '688036', '300782', '002371', '300661',
                '002156', '300373', '300782', '688256', '000977', '300672'
            ],
            ThemeType.AUTO: [
                '000625', '002594', '600104', '000338', '002035', '600066',
                '000800', '300750', '002920', '688099', '002050', '601633'
            ],
            ThemeType.REAL_ESTATE: [
                '000002', '001979', '600383', '000656', '600340', '000069',
                '001872', '600606', '000537', '600823', '000514', '600895'
            ],
            ThemeType.ENVIRONMENT: [
                '000544', '300070', '300152', '002672', '300072', '000826',
                '600388', '300187', '603568', '300422', '002310', '000598'
            ],
            ThemeType.AVIATION: [
                '000738', '600150', '002013', '000901', '600893', '600372',
                '002151', '000043', '002465', '600038', '600118', '000519'
            ],
            ThemeType.CHEMICAL: [
                '000422', '002648', '000792', '600309', '000830', '002192',
                '600160', '002648', '000698', '600688', '300487', '601216'
            ],
            ThemeType.AGRICULTURE: [
                '002234', '000998', '000061', '300189', '002041', '000735',
                '600438', '000876', '002746', '300106', '600095', '002311'
            ],
            ThemeType.COMMUNICATION: [
                '600050', '000063', '002313', '600198', '000938', '002148',
                '300134', '600776', '002281', '002017', '600289', '600522'
            ],
            ThemeType.EDUCATION: [
                '300338', '002607', '002230', '300297', '002659', '300359',
                '002841', '300282', '002261', '300264', '002621', '300365'
            ],
            ThemeType.TOURISM: [
                '600138', '000978', '000524', '600258', '000802', '600749',
                '000721', '600054', '600640', '002033', '600706', '000430'
            ],
            ThemeType.MEDIA: [
                '600880', '000917', '002292', '600825', '300251', '002027',
                '000156', '300113', '002343', '600633', '000793', '002103'
            ],
            ThemeType.SUPPLY_CHAIN: [
                '002352', '000090', '600233', '000061', '002024', '300711',
                '002120', '600795', '300084', '000089', '002468', '600009'
            ],
            ThemeType.BIOTECH: [
                '300122', '688185', '688221', '000661', '300294', '002390',
                '300267', '688139', '300142', '300298', '000078', '300357'
            ],
            ThemeType.FINTECH: [
                '300059', '002537', '002065', '300033', '300418', '300036',
                '002177', '300496', '000783', '600570', '300168', '300369'
            ],
            ThemeType.INTERNET: [
                '300059', '002024', '300033', '002195', '300383', '300628',
                '002373', '300426', '000063', '300418', '002103', '300364'
            ],
            ThemeType.GAMING: [
                '002354', '300059', '300052', '002174', '300431', '300148',
                '000681', '300459', '002425', '300251', '002400', '300315'
            ],
            ThemeType.ESG: [
                '000858', '300750', '002415', '600519', '000002', '000001',
                '300015', '002304', '600036', '300014', '002594', '600276'
            ],
            ThemeType.METAVERSE: [
                '300059', '002354', '002174', '300431', '300052', '000063',
                '300148', '002425', '300251', '300315', '002400', '000681'
            ],
            ThemeType.BLOCKCHAIN: [
                '300059', '002537', '300033', '000063', '002373', '300418',
                '002065', '600570', '002177', '300168', '002195', '300628'
            ],
            ThemeType.QUANTUM: [
                '002049', '600460', '000988', '600990', '000839', '000988',
                '002281', '300102', '300773', '002912', '600570', '688700'
            ]
        }
    
    def _init_monthly_patterns(self) -> List[MonthlyThemePattern]:
        """初始化月度题材炒作规律"""
        return [
            MonthlyThemePattern(
                month=1,
                hot_themes=["新能源", "消费", "金融", "基建"],
                success_rate=0.75,
                typical_duration="2-3周",
                historical_notes="年初资金入市，新能源年度规划题材活跃，春节消费概念升温"
            ),
            MonthlyThemePattern(
                month=2,
                hot_themes=["消费", "旅游酒店", "传媒", "农业"],
                success_rate=0.70,
                typical_duration="1-2周",
                historical_notes="春节消费高峰，旅游复苏预期，传媒春晚效应，农业春耕准备"
            ),
            MonthlyThemePattern(
                month=3,
                hot_themes=["新能源", "半导体芯片", "人工智能", "医药医疗"],
                success_rate=0.80,
                typical_duration="3-4周",
                historical_notes="两会政策风向，科技创新热点，医药进入业绩验证期"
            ),
            MonthlyThemePattern(
                month=4,
                hot_themes=["农业", "消费", "旅游酒店", "环保"],
                success_rate=0.65,
                typical_duration="2-3周",
                historical_notes="春季农业题材，五一旅游预期，环保政策落地期"
            ),
            MonthlyThemePattern(
                month=5,
                hot_themes=["科技股", "新能源", "消费", "房地产"],
                success_rate=0.72,
                typical_duration="2-3周",
                historical_notes="科技股财报季，新能源政策密集期，消费复苏验证"
            ),
            MonthlyThemePattern(
                month=6,
                hot_themes=["教育", "消费", "医药医疗", "半导体芯片"],
                success_rate=0.68,
                typical_duration="1-2周",
                historical_notes="高考教育概念，中报预期，医药进入淡季前的最后冲刺"
            ),
            MonthlyThemePattern(
                month=7,
                hot_themes=["旅游酒店", "消费", "军工", "新能源"],
                success_rate=0.75,
                typical_duration="3-4周",
                historical_notes="暑假旅游高峰，建军节军工概念，新能源装机旺季"
            ),
            MonthlyThemePattern(
                month=8,
                hot_themes=["军工", "消费", "教育", "科技股"],
                success_rate=0.73,
                typical_duration="2-3周",
                historical_notes="军工装备列装期，开学季教育概念，科技股中报披露"
            ),
            MonthlyThemePattern(
                month=9,
                hot_themes=["消费", "科技股", "金融", "周期"],
                success_rate=0.78,
                typical_duration="3-4周",
                historical_notes="中秋国庆双节消费，科技股秋季发布会，金融股估值修复"
            ),
            MonthlyThemePattern(
                month=10,
                hot_themes=["消费", "旅游酒店", "新能源", "军工"],
                success_rate=0.76,
                typical_duration="2-3周",
                historical_notes="国庆黄金周，军工装备展示，新能源四季度冲刺"
            ),
            MonthlyThemePattern(
                month=11,
                hot_themes=["消费", "医药医疗", "新能源", "科技股"],
                success_rate=0.82,
                typical_duration="3-4周",
                historical_notes="双十一消费节，医药进入旺季，新能源年底抢装，科技股财报预期"
            ),
            MonthlyThemePattern(
                month=12,
                hot_themes=["消费", "医药医疗", "金融", "新能源"],
                success_rate=0.80,
                typical_duration="4-5周",
                historical_notes="年底消费旺季，医药进入流感季，银行年末冲业绩，新能源抢装潮"
            )
        ]
    
    def test_connection(self) -> bool:
        """测试数据连接"""
        try:
            test_stocks = ['601611']  # 用中国核建测试
            quotes = self.quotation.stocks(test_stocks)
            return bool(quotes)
        except Exception as e:
            self.logger.error(f"连接测试失败：{e}")
            return False
    
    def analyze_market_themes(self) -> List[ThemeAnalysis]:
        """分析市场主要题材"""
        self.logger.info("开始分析市场题材热度...")
        theme_analyses = []
        
        for theme, stock_codes in self.theme_stocks.items():
            try:
                # 获取该题材股票数据
                quotes = self.quotation.stocks(stock_codes[:10])  # 限制每个题材最多10只股票
                
                if not quotes:
                    continue
                
                # 分析题材数据
                analysis = self._analyze_single_theme(theme, quotes)
                theme_analyses.append(analysis)
                
                # 避免请求过快
                time.sleep(0.1)
                
            except Exception as e:
                self.logger.warning(f"分析题材 {theme.value} 时出错：{e}")
                continue
        
        # 按热度排序
        theme_analyses.sort(key=lambda x: x.hot_score, reverse=True)
        return theme_analyses
    
    def _analyze_single_theme(self, theme: ThemeType, quotes: Dict) -> ThemeAnalysis:
        """分析单个题材"""
        stock_infos = []
        total_change = 0
        total_volume = 0
        positive_count = 0
        
        for code, data in quotes.items():
            try:
                # 解析股票数据
                stock_info = self._parse_stock_data(code, data, theme)
                stock_infos.append(stock_info)
                
                total_change += stock_info.change_pct
                total_volume += stock_info.volume
                
                if stock_info.change_pct > 0:
                    positive_count += 1
                    
            except Exception as e:
                self.logger.debug(f"解析股票 {code} 数据失败：{e}")
                continue
        
        if not stock_infos:
            # 返回默认分析结果
            return ThemeAnalysis(
                theme=theme,
                hot_score=0,
                trend_score=0,
                risk_score=50,
                top_stocks=[],
                recommendation="暂无数据"
            )
        
        # 计算题材评分
        avg_change = total_change / len(stock_infos)
        positive_ratio = positive_count / len(stock_infos)
        
        # 热度评分 (基于平均涨幅和上涨个股比例)
        hot_score = min(100, max(0, (avg_change * 10 + positive_ratio * 50)))
        
        # 趋势评分 (基于连续性和稳定性)
        trend_score = min(100, max(0, (positive_ratio * 60 + (1 - abs(avg_change - 5)) * 40)))
        
        # 风险评分 (波动性评估)
        volatility = sum(abs(s.change_pct - avg_change) for s in stock_infos) / len(stock_infos)
        risk_score = min(100, max(0, volatility * 10 + 30))
        
        # 选择表现最好的股票
        top_stocks = sorted(stock_infos, key=lambda x: x.score, reverse=True)[:5]
        
        # 生成推荐建议
        recommendation = self._generate_theme_recommendation(hot_score, trend_score, risk_score)
        
        return ThemeAnalysis(
            theme=theme,
            hot_score=hot_score,
            trend_score=trend_score,
            risk_score=risk_score,
            top_stocks=top_stocks,
            recommendation=recommendation
        )
    
    def _parse_stock_data(self, code: str, data: Dict, theme: ThemeType) -> StockInfo:
        """解析股票数据"""
        try:
            # 获取基本信息
            name = data.get('name', f'股票{code}')
            
            # 获取价格信息
            price = float(data.get('now', data.get('close', data.get('price', 0))))
            close_price = float(data.get('close', price))
            
            # 获取涨跌幅信息
            if '涨跌(%)' in data:
                # 腾讯数据源
                change_pct = float(data.get('涨跌(%)', 0))
            elif 'percent' in data:
                # 其他数据源可能用percent字段
                change_pct = float(data.get('percent', 0))
            else:
                # 新浪数据源需要手动计算涨跌幅
                if close_price > 0 and price > 0:
                    change_pct = ((price - close_price) / close_price) * 100
                else:
                    change_pct = 0
            
            # 获取成交量
            volume_field = data.get('turnover', data.get('volume', data.get('成交量(手)', 0)))
            volume = int(volume_field) if volume_field else 0
            
            # 计算市值 (简化计算)
            market_cap = price * volume / 10000 if volume > 0 else 0
            
            # 计算综合评分
            score = self._calculate_stock_score(price, change_pct, volume)
            
            # 评估风险等级
            risk_level = self._assess_risk_level(change_pct, volume, market_cap)
            
            return StockInfo(
                code=code,
                name=name,
                price=price,
                change_pct=change_pct,
                volume=volume,
                market_cap=market_cap,
                theme=theme,
                score=score,
                risk_level=risk_level
            )
            
        except Exception as e:
            self.logger.debug(f"解析股票 {code} 数据时出错：{e}")
            # 返回默认值
            return StockInfo(
                code=code,
                name=f'股票{code}',
                price=0,
                change_pct=0,
                volume=0,
                market_cap=0,
                theme=theme,
                score=0,
                risk_level=RiskLevel.MEDIUM
            )
    
    def _calculate_stock_score(self, price: float, change_pct: float, volume: int) -> float:
        """计算股票综合评分"""
        # 基础分数
        base_score = 50
        
        # 涨幅得分 (涨幅在3-7%之间得分最高)
        if 3 <= change_pct <= 7:
            change_score = 30
        elif 0 <= change_pct < 3:
            change_score = change_pct * 10
        elif change_pct > 7:
            change_score = max(0, 30 - (change_pct - 7) * 2)
        else:
            change_score = 0
        
        # 成交量得分 (成交量越大得分越高，但有上限)
        volume_score = min(20, volume / 1000000)  # 每百万成交量得1分，上限20分
        
        return base_score + change_score + volume_score
    
    def _assess_risk_level(self, change_pct: float, volume: int, market_cap: float) -> RiskLevel:
        """评估股票风险等级"""
        risk_score = 0
        
        # 涨跌幅风险
        if abs(change_pct) > 8:
            risk_score += 2
        elif abs(change_pct) > 5:
            risk_score += 1
        
        # 流动性风险
        if volume < 10000:
            risk_score += 2
        elif volume < 50000:
            risk_score += 1
        
        # 市值风险
        if market_cap < 100:
            risk_score += 1
        
        if risk_score >= 4:
            return RiskLevel.VERY_HIGH
        elif risk_score >= 3:
            return RiskLevel.HIGH
        elif risk_score >= 2:
            return RiskLevel.MEDIUM
        else:
            return RiskLevel.LOW
    
    def _generate_theme_recommendation(self, hot_score: float, trend_score: float, risk_score: float) -> str:
        """生成题材推荐建议"""
        if hot_score >= 70 and trend_score >= 60 and risk_score <= 50:
            return "🔥 强烈推荐：题材热度高，趋势良好，风险可控"
        elif hot_score >= 50 and trend_score >= 50:
            return "👍 推荐关注：题材具有投资价值，建议适量配置"
        elif hot_score >= 30:
            return "⚠️ 谨慎观望：题材热度一般，建议观察后续走势"
        else:
            return "❌ 不建议投资：题材表现较差，建议回避"
    
    def intelligent_stock_selection(self, max_selections: int = 10) -> SelectionResult:
        """智能选股主函数 - 集成DeepSeek AI分析"""
        self.logger.info(f"开始AI智能选股分析，目标选择 {max_selections} 只股票...")
        
        # 1. 分析市场题材
        theme_analyses = self.analyze_market_themes()
        
        # 2. 收集所有候选股票
        all_candidates = []
        for analysis in theme_analyses:
            all_candidates.extend(analysis.top_stocks)
        
        # 3. 根据综合评分排序选股
        all_candidates.sort(key=lambda x: x.score, reverse=True)
        recommended_stocks = all_candidates[:max_selections]
        
        # 4. 生成市场概况
        market_overview = self._generate_market_overview(theme_analyses)
        
        # 5. 集成DeepSeek AI分析
        ai_analysis = None
        if self.use_ai and self.deepseek_ai:
            try:
                self.logger.info("正在进行DeepSeek AI深度分析...")
                
                # 准备AI分析数据
                theme_data = []
                for analysis in theme_analyses[:5]:  # 只分析前5个热门题材
                    theme_data.append({
                        'name': analysis.theme.value,
                        'hot_score': analysis.hot_score,
                        'trend_score': analysis.trend_score,
                        'risk_score': analysis.risk_score,
                        'recommendation': analysis.recommendation
                    })
                
                ai_analysis = self.deepseek_ai.analyze_market_data(market_overview, theme_data)
                self.logger.info(f"AI分析完成，置信度: {ai_analysis.confidence_score:.1f}%")
                
            except Exception as e:
                self.logger.warning(f"AI分析失败: {e}")
        
        # 6. 生成风险警示 (考虑AI分析结果)
        risk_warning = self._generate_enhanced_risk_warning(recommended_stocks, ai_analysis)
        
        # 7. 生成策略建议 (考虑AI分析结果)
        strategy_advice = self._generate_enhanced_strategy_advice(theme_analyses, recommended_stocks, ai_analysis)
        
        # 8. 获取当前月度炒作规律
        current_month = datetime.now().month
        current_month_pattern = next((p for p in self.monthly_patterns if p.month == current_month), None)
        
        return SelectionResult(
            recommended_stocks=recommended_stocks,
            theme_analysis=theme_analyses,
            market_overview=market_overview,
            risk_warning=risk_warning,
            strategy_advice=strategy_advice,
            ai_analysis=ai_analysis,
            monthly_patterns=self.monthly_patterns if current_month_pattern else None
        )
    
    def _generate_market_overview(self, theme_analyses: List[ThemeAnalysis]) -> Dict:
        """生成市场概况"""
        if not theme_analyses:
            return {"status": "无数据", "hot_themes": [], "avg_score": 0}
        
        # 计算平均热度
        avg_hot_score = sum(t.hot_score for t in theme_analyses) / len(theme_analyses)
        
        # 找出热门题材
        hot_themes = [t.theme.value for t in theme_analyses[:3] if t.hot_score >= 50]
        
        # 市场状态评估
        if avg_hot_score >= 60:
            market_status = "活跃"
        elif avg_hot_score >= 40:
            market_status = "平稳"
        else:
            market_status = "低迷"
        
        return {
            "status": market_status,
            "avg_score": round(avg_hot_score, 1),
            "hot_themes": hot_themes,
            "total_themes": len(theme_analyses)
        }
    
    def _generate_risk_warning(self, stocks: List[StockInfo]) -> str:
        """生成风险警示"""
        if not stocks:
            return "⚠️ 无推荐股票，市场风险较高，建议观望"
        
        high_risk_count = sum(1 for s in stocks if s.risk_level in [RiskLevel.HIGH, RiskLevel.VERY_HIGH])
        high_risk_ratio = high_risk_count / len(stocks)
        
        if high_risk_ratio >= 0.5:
            return "🚨 高风险警告：超过50%的推荐股票存在高风险，请谨慎投资，控制仓位"
        elif high_risk_ratio >= 0.3:
            return "⚠️ 中度风险：部分推荐股票存在较高风险，建议分散投资，设置止损"
        else:
            return "✅ 风险可控：大部分推荐股票风险较低，但仍需关注市场变化"
    
    def _generate_enhanced_risk_warning(self, stocks: List[StockInfo], ai_analysis: Optional[AIAnalysisResult]) -> str:
        """生成增强的风险警示 (考虑AI分析结果)"""
        if not stocks:
            return "⚠️ 无推荐股票，市场风险较高，建议观望"
        
        high_risk_count = sum(1 for s in stocks if s.risk_level in [RiskLevel.HIGH, RiskLevel.VERY_HIGH])
        high_risk_ratio = high_risk_count / len(stocks)
        
        # 基础风险评估
        if high_risk_ratio >= 0.5:
            base_warning = "🚨 高风险警告：超过50%的推荐股票存在高风险，请谨慎投资，控制仓位"
        elif high_risk_ratio >= 0.3:
            base_warning = "⚠️ 中度风险：部分推荐股票存在较高风险，建议分散投资，设置止损"
        else:
            base_warning = "✅ 风险可控：大部分推荐股票风险较低，但仍需关注市场变化"
        
        # 融合AI分析的风险评估
        if ai_analysis and ai_analysis.confidence_score > 70:
            ai_risk_note = f"\n🤖 AI风险评估: {ai_analysis.risk_assessment} (置信度: {ai_analysis.confidence_score:.1f}%)"
            return base_warning + ai_risk_note
        
        return base_warning
    
    def _generate_enhanced_strategy_advice(self, theme_analyses: List[ThemeAnalysis], 
                                         stocks: List[StockInfo], 
                                         ai_analysis: Optional[AIAnalysisResult]) -> str:
        """生成增强的投资策略建议 (考虑AI分析结果)"""
        if not theme_analyses or not stocks:
            return "建议观望，等待更好的投资机会"
        
        # 获取最热门的题材
        top_theme = theme_analyses[0] if theme_analyses else None
        
        # 计算平均涨幅
        avg_change = sum(s.change_pct for s in stocks) / len(stocks) if stocks else 0
        
        # 当前月份的炒作规律
        current_month = datetime.now().month
        current_pattern = next((p for p in self.monthly_patterns if p.month == current_month), None)
        
        advice = f"""
💡 投资策略建议：

🎯 重点关注题材：{top_theme.theme.value if top_theme else '暂无'}
📊 当前市场平均涨幅：{avg_change:.2f}%"""
        
        # 添加AI分析建议
        if ai_analysis and ai_analysis.confidence_score > 60:
            advice += f"""
🤖 AI市场判断：{ai_analysis.market_sentiment} | 趋势预测：{ai_analysis.trend_prediction}
💡 AI投资建议：{ai_analysis.investment_suggestion}"""
        
        # 添加月度炒作规律
        if current_pattern:
            advice += f"""

📅 {current_month}月炒作规律：
🔥 历史热门题材：{', '.join(current_pattern.hot_themes)}
📈 成功率：{current_pattern.success_rate*100:.0f}% | 持续时间：{current_pattern.typical_duration}
📝 历史特点：{current_pattern.historical_notes}"""
        
        advice += """

🏗️ 建议投资策略：
1. 分批建仓：不要一次性投入，建议分3-5次建仓
2. 止损设置：建议设置8-10%的止损线
3. 题材轮动：关注热点题材的轮动机会
4. 风险控制：单只股票不超过总资金的10%

⏰ 操作建议：
- 适合短线：涨幅3-7%的股票
- 适合中线：基本面良好的低估值股票
- 注意避险：涨幅过大(>8%)的股票需谨慎"""
        
        return advice.strip()
    
    def _generate_strategy_advice(self, theme_analyses: List[ThemeAnalysis], stocks: List[StockInfo]) -> str:
        """生成投资策略建议 (保留原函数兼容性)"""
        return self._generate_enhanced_strategy_advice(theme_analyses, stocks, None)
    
    def display_selection_result(self, result: SelectionResult):
        """显示选股结果"""
        print("\n" + "="*80)
        print("🤖 DeepSeek AI智能选股分析报告")
        print("="*80)
        
        # 显示AI分析状态
        if result.ai_analysis:
            print(f"✅ DeepSeek AI分析已启用 (置信度: {result.ai_analysis.confidence_score:.1f}%)")
        else:
            print("⚠️ 使用传统算法分析 (DeepSeek AI未启用)")
        
        # 市场概况
        print(f"\n📊 市场概况:")
        overview = result.market_overview
        print(f"   市场状态: {overview.get('status', '未知')}")
        print(f"   平均热度: {overview.get('avg_score', 0)}")
        print(f"   热门题材: {', '.join(overview.get('hot_themes', []))}")
        
        # 显示AI分析结果
        if result.ai_analysis:
            print(f"\n🤖 DeepSeek AI市场分析:")
            print(f"   市场情绪: {result.ai_analysis.market_sentiment}")
            print(f"   趋势预测: {result.ai_analysis.trend_prediction}")
            print(f"   风险评估: {result.ai_analysis.risk_assessment}")
        
        # 显示当前月度炒作规律
        current_month = datetime.now().month
        if result.monthly_patterns:
            current_pattern = next((p for p in result.monthly_patterns if p.month == current_month), None)
            if current_pattern:
                print(f"\n📅 {current_month}月炒作规律:")
                print(f"   历史热门: {', '.join(current_pattern.hot_themes)}")
                print(f"   成功率: {current_pattern.success_rate*100:.0f}% | 持续: {current_pattern.typical_duration}")
                print(f"   特点: {current_pattern.historical_notes}")
        
        # 题材分析
        print(f"\n🎯 题材热度排行:")
        for i, analysis in enumerate(result.theme_analysis[:5], 1):
            print(f"   {i}. {analysis.theme.value}")
            print(f"      热度: {analysis.hot_score:.1f} | 趋势: {analysis.trend_score:.1f} | 风险: {analysis.risk_score:.1f}")
            print(f"      建议: {analysis.recommendation}")
        
        # 推荐股票
        print(f"\n⭐ 推荐股票 (Top {len(result.recommended_stocks)}):")
        print(f"{'排名':<4} {'代码':<8} {'名称':<12} {'价格':<8} {'涨幅':<8} {'评分':<6} {'风险':<8} {'题材':<10}")
        print("-" * 80)
        
        for i, stock in enumerate(result.recommended_stocks, 1):
            print(f"{i:<4} {stock.code:<8} {stock.name:<12} {stock.price:<8.2f} "
                  f"{stock.change_pct:<8.2f}% {stock.score:<6.1f} {stock.risk_level.value[0]:<8} {stock.theme.value:<10}")
        
        # 风险警示
        print(f"\n⚠️  风险提示:")
        print(f"   {result.risk_warning}")
        
        # 策略建议
        print(f"\n{result.strategy_advice}")
        
        print("\n" + "="*80)
        print("📢 免责声明：本分析结合DeepSeek AI技术，但仅供参考，不构成投资建议。")
        print("AI分析存在不确定性，投资有风险，入市需谨慎！")
        print("="*80)
    
    def display_monthly_patterns_only(self):
        """仅显示月度炒作规律"""
        print("\n" + "="*80)
        print("📅 A股月度题材炒作规律分析")
        print("="*80)
        
        current_month = datetime.now().month
        
        for pattern in self.monthly_patterns:
            is_current = pattern.month == current_month
            status = "📍 当前月份" if is_current else ""
            
            print(f"\n{'🔥' if is_current else '📅'} {pattern.month}月 {status}")
            print(f"   热门题材: {', '.join(pattern.hot_themes)}")
            print(f"   成功率: {pattern.success_rate*100:.0f}% | 持续时间: {pattern.typical_duration}")
            print(f"   历史特点: {pattern.historical_notes}")
            
            if is_current:
                print("   ⚡ 本月重点关注以上题材的投资机会")
        
        print(f"\n💡 使用建议:")
        print("1. 结合月度规律进行题材轮动布局")
        print("2. 在成功率高的月份加大投资力度") 
        print("3. 注意持续时间，避免追高杀跌")
        print("4. 历史规律仅供参考，需结合实际市场情况")
        
        print(f"\n📋 数据说明:")
        print("以上数据基于历史统计分析，成功率为历史平均水平")
        print("市场有风险，投资需谨慎，请勿完全依赖历史规律")
        print("="*80)


def create_ai_selector(data_source: str = 'tencent') -> AIStockSelector:
    """创建AI选股器实例
    
    Args:
        data_source: 数据源类型
        
    Returns:
        AIStockSelector: AI选股器实例
    """
    return AIStockSelector(data_source=data_source)


if __name__ == "__main__":
    # 测试代码
    selector = create_ai_selector()
    if selector.test_connection():
        result = selector.intelligent_stock_selection(5)
        selector.display_selection_result(result)
    else:
        print("数据源连接失败") 